package com.itheima.security.distributed.uaa.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itheima.security.distributed.uaa.model.User;
import com.itheima.security.distributed.uaa.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author xiaoxiaokui
 * @description: SpringDataUserDetailsService
 * @date 2019/11/19
 **/
@Service
public class SpringDataUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    /**
     * @author xiaoxiaokui
     * @description 根据账号查询用户信息
     * @date 2019/11/19
     * @param username
     * @return org.springframework.security.core.userdetails.UserDetails
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 将来链接数据库，根据账号查询用户信息
        User userDto = userService.getOne((Wrappers.<User>lambdaQuery().eq(User::getUsername, username)).last("limit 1"));
        if (userDto == null) {
            // 如果用户查不到，返回null，由provider来抛出异常
            return null;
        }
        System.out.println("username = " + username);
        // 根据用户的id查询用户的权限
        List<String> permissions = userService.findPermissionCodeListByUserId(userDto.getId());
        // 将permissions转成数组
        String[] permissionArray = new String[permissions.size()];
        permissions.toArray(permissionArray);
        // 暂时采用模拟方式
        // 将userDto 转成 json
        String principal = JSON.toJSONString(userDto);
        UserDetails userDetails = org.springframework.security.core.userdetails.User
                .withUsername(principal)
                .password(userDto.getPassword())
                .authorities(permissionArray)
                .build();
        return userDetails;
    }
}
